import storage from '../../utils/storage'

const datafeedConfig = (params) => {
  const {resolution, language,colorUp,colorDown, timezone, Datafeeds, serverUrl, pushInterval, initParams} = params;
  this.resolution = resolution;

  return {
    //debug: true,
    autosize:true,
    fullscreen: false,
    symbol: initParams.symbolName,
    interval: resolution,
    timezone: timezone,
    container_id: 'tv_chart_container',
    datafeed: new Datafeeds.UDFCompatibleDatafeed(serverUrl, pushInterval, null, initParams),
    width: '100%',
    height: '100%',
    library_path: "../../../static/tradeView/charting_library/",// libraryPath: 'http://192.168.6.75/charting_library/',
    locale: language,
    drawings_access: {
      type: 'black',
      tools: [{
        name: 'Regression Trend',
      }],
    },
    disabled_features: [
      //"compare_symbol",
      "display_market_status",//显示市场状态（开盘 收盘 等）
      "go_to_date",
      "header_chart_type",//显示图表类型按钮
      "header_compare",
      "header_interval_dialog_button",
      "header_resolutions",//周期设置按钮
      "header_screenshot",//截屏按钮
      "header_symbol_search",//品种搜索框
      "header_undo_redo",//撤销、重做按钮
      "header_saveload",//保存图表，加载图表按钮
      "legend_context_menu",
      "show_hide_button_in_legend",
      "show_interval_dialog_on_key_press",
      "snapshot_trading_drawings",
      "symbol_info",//商品信息对话框
      "timeframes_toolbar",
      "pane_context_menu",
      "control_bar",//前进 后退 放大 缩小
      //"edit_buttons_in_legend", //在元素信息中显示“设置”按钮
      "source_selection_markers",
      "use_localstorage_for_settings",//允许将用户设置保存到localstorage
      "volume_force_overlay", //在与主数据列相同的窗格中放置成交量指示器
      //"high_density_bars", //允许缩小在1个屏幕上显示超过60000条个K线
      "save_chart_properties_to_local_storage",
      "header_fullscreen_button",  //隐藏头部全屏按钮
      //"side_toolbar_in_fullscreen_mode",//使用此功能，您可以在全屏模式下启用绘图工具栏
    ],
    enabled_features:[

      //"hide_last_na_study_output",
      //"move_logo_to_main_pane",//将标志放在主数据列窗格上，而不是底部窗格
      //"same_data_requery",
      "hide_left_toolbar_by_default",//当用户第一次打开时隐藏左侧工具栏
      "keep_left_toolbar_visible_on_small_screens",//防止左侧工具栏在小屏幕上消失
      "dont_show_boolean_study_arguments",//是否隐藏指标参数
      //"keep_left_toolbar_visible_on_small_screens",//防止左侧工具栏在小屏幕上消失
      //"disable_resolution_rebuild"
    ],
      // preset: "mobile",
      toolbar_bg: "#1E212B",//工具栏背景颜色
      loading_screen: {
      backgroundColor: "#1E212B",//加载时的背景颜色
        foregroundColor: "#346ab3",//加载时图标颜色
    },
    charts_storage_url: 'http://saveload.tradingview.com',
    charts_storage_api_version: '1.1',
    client_id: 'tradingview.com',
    user_id: 'public_user_id',
    /*time_frames: [
      { text: "1min", resolution: "5s", description: "1 min" },
      { text: "1h", resolution: "1", description: "1 hour" },
      { text: "1d", resolution: "5", description: "1 Days" },
    ],*/
    overrides: {
      //蜡烛样式
      "mainSeriesProperties.candleStyle.upColor": colorUp,//绿
      "mainSeriesProperties.candleStyle.downColor": colorDown,//红
      //烛心
      "mainSeriesProperties.candleStyle.drawWick": true,
      //烛心颜色
      "mainSeriesProperties.candleStyle.wickUpColor": colorUp,
      "mainSeriesProperties.candleStyle.wickDownColor": colorDown,
      //边框
      "mainSeriesProperties.candleStyle.drawBorder": true,
      "mainSeriesProperties.candleStyle.borderUpColor": colorUp,
      "mainSeriesProperties.candleStyle.borderDownColor": colorDown,

      "symbolWatermarkProperties.color":"rgba(0, 0, 0, 0)",//水印100％不透明（不可见）
      "paneProperties.background": "#1E212B",//整体背景颜色
      "symbolWatermarkProperties.transparency": 100,
      //网格线
      "paneProperties.topMargin": 15,
      "paneProperties.bottomMargin": 0,
      "paneProperties.vertGridProperties.color": "#242833",
      "paneProperties.vertGridProperties.style": 0,
      "paneProperties.horzGridProperties.color": "#242833",
      "paneProperties.horzGridProperties.style": 0,
      'paneProperties.legendProperties.showLegend': false,  //隐藏交易对名字

      //"timeScale.rightOffset": 10,
      // "paneProperties.crossHairProperties.color": "#ffffff",
      //坐标轴和刻度标签颜色
      "scalesProperties.textColor" : "#666870",
      "scalesProperties.lineColor": "#32343E",
      //成交量高度
      "volumePaneSize": "medium",//支持的值: large, medium, small, tiny

      // "MACDPaneSize":"tiny"
    },
    studies_overrides: {
      "volume.volume.color.0": colorDown,
      "volume.volume.color.1": colorUp,
      "volume.volume.transparency": 100,

      "MA Cross.short:plot.color": "#6B3798",
      "MA Cross.long:plot.color": "#708957",
      //"MA Cross.crosses:plot.color": "#f00", //
      "MA Cross.crosses:plot.linewidth": 0,
      "MA Cross.short:plot.linewidth": 1.5,
      "MA Cross.long:plot.linewidth": 1.5
    },
  };
};

const chartReady = (widget, that) => {
  //默认展示MA Cross
  widget.chart().createStudy("MA Cross", false, false, [7, 30]);
  const buttonArr = [
    {
      value: '-1',
      period: '1min',
      text: that.$t("commonKline_line"),
      chartType: 3,
    },
    {
      value: '1',
      period: '1min',
      text: that.$t("commonKline_1min"),
    },
    {
      value: '5',
      period: '5min',
      text: that.$t("commonKline_5min"),
    },
    {
      value: '15',
      period: '15min',
      text: that.$t("commonKline_15min"),
    },
    {
      value: '30',
      period: '30min',
      text: that.$t("commonKline_30min"),
    },
    {
      value: '60',
      period: '1hour',
      text: that.$t("commonKline_1hour"),
    },
    {
      value: '240',
      period: '4hour',
      text: that.$t("commonKline_4hour"),
    },
    {
      value: '1D',
      period: '1day',
      text: that.$t("commonKline_1day"),
    },
    {
      value: '1W',
      period: '1week',
      text: that.$t("commonKline_1week"),
    },
    /*{
      value: '1M',
      period: '1M',
      text: '月线',
    },*/
  ];

  let btn = {};
  const handleClick = (e, value) => {
    widget.chart().setResolution(value);
    $(e.target).parents(".left").children().find(".mydate").removeClass("mydate-active");
    $(e.target).addClass("mydate-active");
  };

  let klineType;
  let klineTypeOption = storage.getData("resolutionOption");
  if(location.href.toLowerCase().indexOf("/option") != -1){
    if(!klineTypeOption){
      if(this.resolution){
        klineType = this.resolution;
      }
    }else{
      klineType = klineTypeOption;
    }
  }else{
    klineType = storage.getData("resolutionSpot") || 15;
  }

  buttonArr.forEach((v, i) => {

    if (v.value == klineType) {
      btn = widget.createButton().addClass("mydate mydate-active").on('click', (e) => {
        if(location.href.toLowerCase().indexOf("/option") != -1){
          storage.setData("resolutionOption", v.value);
        }else{
          storage.setData("resolutionSpot", v.value);
        }
        handleClick(e, v.value)
      });
    } else {
      btn = widget.createButton().addClass("mydate").on('click', (e) => {
        if(location.href.toLowerCase().indexOf("/option") != -1){
          storage.setData("resolutionOption", v.value);
        }else{
          storage.setData("resolutionSpot", v.value);
        }
        handleClick(e, v.value)
      });
    }

    btn[0].innerHTML = v.text;
    btn[0].title = v.text;
  });
  /*$(document).ready(function () {
    /!** Coding Here *!/
  }).keydown(function (e) {
    if (e.which === 27) {
      /!** 这里编写当ESC按下时的处理逻辑！ *!/
      alert(22)
    }
  });*/
    const buttonEvent = widget.createButton({align: "right"});
    const button = buttonEvent[0];
    button.title = '打开/关闭全屏';
    button.className = 'button fullscreen iconed apply-common-tooltip';
    buttonEvent.append($('<span class="icon-full"><img src="/static/images/iconfull.png"></span>')); //图片地址
    button.onclick = function() {
      const tvid = $('#tv_chart_container')[0];
      if (tvid.className === 'tv_chart_container_full') {
        tvid.className = '';
        return;
      }
      tvid.className = 'tv_chart_container_full';
    }

  };
/**
 * 计算两个时间的相差小时选中默认的分辨率
 * @param startDate
 * @param endDate
 * @returns {*}
 */
const getIntervalHour = (startDate, endDate) => {
  const ms = endDate - startDate;
  const hour = Number(ms/1000/60/60);
  if(startDate){
    if(!isNaN(hour) && hour > 0){
      let symbolTime;
      if(hour > 144){
        symbolTime = "240";
      }else if(hour > 48){
        symbolTime = "60";
      }else if(hour > 24){
        symbolTime = "30";
      }else if(hour > 8){
        symbolTime = "15";
      }else if(hour > 1){
        symbolTime = "5";
      }else if(hour > -1){
        symbolTime = "1";
      }
      return symbolTime;
    }
  }
  return null;
}

export default {
  getIntervalHour,
  datafeedConfig,
  chartReady,
};
